/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.controller.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.AbstractController;

import com.sesame.domain.Admin;
import com.sesame.service.AdminService;

/**
 * @author r6c
 * 
 */
public class ModifyPasswordController extends AbstractController {

    private AdminService adminService;
    private Admin admin;

    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        if (request.getSession().getAttribute("adminRank") != null) {
            String oldPassword = request.getParameter("oldPassword");
            String password = request.getParameter("password");
            String confirmPassword = request.getParameter("confirmPassword");
            if (oldPassword != null) {
                admin.setId((Integer) request.getSession().getAttribute(
                        "adminId"));
                admin.setPassword(password);
                Map model = new HashMap();

                boolean isRightPassword = adminService.validatePassword(admin,
                        confirmPassword, model);

                if (!isRightPassword) {
                    return new ModelAndView("admin/modifyPassword", model);
                }

                boolean isModify = adminService.modifyPassword(oldPassword,
                        admin, model);

                if (isModify) {
                    return new ModelAndView("admin/modifyPasswordSuccess",
                            model);
                } else {
                    return new ModelAndView("admin/modifyPassword", model);
                }
            } else {
                return new ModelAndView("admin/modifyPassword");
            }
        } else {
            return new ModelAndView("redirect:adminError.html");
        }

    }
}